package com.lzc.springcloud.msconsumeruser.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.lzc.springcloud.msconsumeruser.entity.User;

@RestController
public class UserController {
	
	/**
	 * Spring's central class for synchronous client-side HTTP access
	 */
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
    private LoadBalancerClient loadBalancer;
	
	/**
	 * 获取application.properties的配置内容
	 */
	@Value("${user.userService}")
	private String userService;
	
	@GetMapping("/getUser/{id}")
	public User getUser(@PathVariable Integer id) {
		
		ServiceInstance instance = this.loadBalancer.choose(userService);
		System.out.println("====" + instance.getServiceId() + ":" + instance.getHost() + ":" + instance.getPort());
		
//		String url = "http://127.0.0.1:7900/getUser/" + id;
		String url = "http://" + userService + "/getUser/" + id;
		
		return this.restTemplate.getForObject(url, User.class);
	}
}
